﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bamboo.Utils
{
    public static class SingleLineString
    {
        /// <summary>
        /// 多行文本转单行
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string FromMultiLine(string input)
        {
            var s = new StringBuilder(input.Length);
            foreach (var ch in input)
            {
                if (ch == '\r') s.Append("\\r");
                else if (ch == '\n') s.Append("\\n");
                else if (ch == ',') s.Append("\\c");
                else if (ch == '\\') s.Append('\\');
                else s.Append(ch);
            }
            return s.ToString();
        }

        /// <summary>
        /// 单行文本转回多行，配对使用。
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToMultiLine(string input)
        {
            var s = new StringBuilder(input.Length);
            int mode = 0;   //0:前一个字符不是\，1:前一个字符是\
            foreach (var ch in input)
            {
                if (mode == 0)
                {
                    if (ch == '\\')
                    {
                        mode = 1;
                    }
                    else
                    {
                        s.Append(ch);
                    }
                }
                else
                {
                    if (ch == '\\')
                    {
                        mode = 0; s.Append('\\');
                    }
                    else if (ch == 'r')
                    {
                        mode = 0; s.Append('\r');
                    }
                    else if (ch == 'n')
                    {
                        mode = 0; s.Append('\n');
                    }
                    else if (ch == 'c')
                    {
                        mode = 0; s.Append(',');
                    }
                    else
                    {
                        mode = 0; s.Append('\\').Append(ch);
                    }
                }
            }
            return s.ToString();
        }
    }
}
